package com.xu.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;



//springsecurity的使用
@EnableWebSecurity  //加载了WebSecurityConfiguration配置类，配置安全认证策略
//加载了AuthenticationConfiguration，配置了认证信息
public class WebSecurity extends WebSecurityConfigurerAdapter {

    //配置拦截方式
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/*").authenticated()     //拦截这些路径
              .antMatchers("/register").hasAuthority("ROLE_ADMIN")      //
                .anyRequest().permitAll()         //其他url开放
                .and()
                .csrf().disable()
                .formLogin().successForwardUrl("/");       //支持form表单认证，认证成功后转向

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("root").password(new BCryptPasswordEncoder().encode("root")).roles("USER","ADMIN").and()
                .withUser("normal").password(new BCryptPasswordEncoder().encode("normal")).roles("USER");
    }
}
